package com.oet.web;


import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;



import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.oet.service.manager.FileManager;



/**
 * Process the login request
 *
 * @author Juergen Hoeller
 * @author Ken Krebs
 */
@Controller
public class WebFileController extends WebControllerBase {
	
//	@Autowired
//	@Qualifier("ydkFrontEndServiceClient")
//    protected YdkFrontEndWebService ydkFrontEndWebService;
//	
//	public void setYdkFrontEndWebService(@Qualifier("ydkFrontEndServiceClient")YdkFrontEndWebService service) {
//        this.ydkFrontEndWebService = service;
//    }
	
	private final Logger logger = Logger.getLogger(WebFileController.class.getName());
//	@Autowired
//	@Qualifier("ydkSimFrontEndServiceClient")
//    protected YdkSimFrontEndService ydkSimFrontEndService;
//	
//	public void seYdkSimFrontEndService(@Qualifier("ydkSimFrontEndServiceClient")YdkSimFrontEndService service) {
//        this.ydkSimFrontEndService = service;
//    }


	
	@RequestMapping(value="/getFile.do", method = RequestMethod.GET)
	public void getImage(ServletWebRequest request, HttpServletResponse response) {
		
		String fileName = request.getParameter("name");
		int length = 0;
		int fileStartLen = 0;
		int fileEndLen = 0;
		String range = request.getRequest().getHeader("RANGE");
		if (range != null && !range.isEmpty())
		{
			int index = range.indexOf("=");
			if (index > 0)
			{
				String continueLengh = range.substring(index + 1).trim();
				
				int splitIndex = continueLengh.indexOf("-");
				if (splitIndex < 0)
				{
					try {
						fileStartLen = Integer.parseInt(continueLengh);
					}catch (NumberFormatException e)
					{
						logger.info("Error input types: " + continueLengh);
						response.setContentLength(length);
						return ;
					}
				}
				else
				{
					String starPos = continueLengh.substring(0, splitIndex).trim();
					String endPos = continueLengh.substring(splitIndex +1).trim();
					try {
						fileStartLen = Integer.parseInt(starPos);
					}catch (NumberFormatException e)
					{
						logger.info("Error input types: " + starPos);
						response.setContentLength(length);
						return ;
					}
					
					try {
						fileEndLen = Integer.parseInt(endPos);
					}catch (NumberFormatException e)
					{
						logger.info("Error input types: " + endPos);
						response.setContentLength(length);
						return ;
					}
					
				}
				
			}
			else
			{
				logger.info("Error input range: " + range);
				response.setContentLength(length);
				return ;
				//error
//				length = 0;
//				response.setContentLength(length);
//				return;
			}
		}

		
		byte[] imgContent = FileManager.loadFile(fileName);
		
		if (imgContent != null)
		{
			int contentLenth = imgContent.length;
			if (fileStartLen > 0 && fileStartLen <= contentLenth)
			{
				
				if (fileEndLen > fileStartLen && fileEndLen <= contentLenth)
				{
					contentLenth = fileEndLen;
				}
				imgContent = Arrays.copyOfRange(imgContent, fileStartLen, contentLenth);
			}
			
			if (imgContent != null)
			{
				try {
					length = imgContent.length;
					response.setContentLength(length);
					FileCopyUtils.copy(imgContent, response.getOutputStream());
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		response.setContentLength(length);
		return ;
	}
	
	
	@RequestMapping(value="/ydkGetContent.do", method = RequestMethod.GET)
	public void getContent(ServletWebRequest request, HttpServletResponse response) {
		
		String fileName = request.getParameter("name");
		int length = 0;
		int fileStartLen = 0;
		int fileEndLen = 0;
		String range = request.getRequest().getHeader("RANGE");
		if (range != null && !range.isEmpty())
		{
			int index = range.indexOf("=");
			if (index > 0)
			{
				String continueLengh = range.substring(index + 1).trim();
				
				int splitIndex = continueLengh.indexOf("-");
				if (splitIndex < 0)
				{
					try {
						fileStartLen = Integer.parseInt(continueLengh);
					}catch (NumberFormatException e)
					{
						logger.info("Error input types: " + continueLengh);
						response.setContentLength(length);
						return ;
					}
				}
				else
				{
					String starPos = continueLengh.substring(0, splitIndex).trim();
					String endPos = continueLengh.substring(splitIndex +1).trim();
					try {
						fileStartLen = Integer.parseInt(starPos);
					}catch (NumberFormatException e)
					{
						logger.info("Error input types: " + starPos);
						response.setContentLength(length);
						return ;
					}
					
					try {
						fileEndLen = Integer.parseInt(endPos);
					}catch (NumberFormatException e)
					{
						logger.info("Error input types: " + endPos);
						response.setContentLength(length);
						return ;
					}
					
				}
				
			}
			else
			{
				logger.info("Error input range: " + range);
				response.setContentLength(length);
				return ;
				//error
//				length = 0;
//				response.setContentLength(length);
//				return;
			}
		}

		
		byte[] imgContent = FileManager.loadFile(fileName);
		
		if (imgContent != null)
		{
			int contentLenth = imgContent.length;
			if (fileStartLen > 0 && fileStartLen <= contentLenth)
			{
				
				if (fileEndLen > fileStartLen && fileEndLen <= contentLenth)
				{
					contentLenth = fileEndLen;
				}
				imgContent = Arrays.copyOfRange(imgContent, fileStartLen, contentLenth);
			}
			
			if (imgContent != null)
			{
				try {
					length = imgContent.length;
					response.setContentLength(length);
					FileCopyUtils.copy(imgContent, response.getOutputStream());
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		response.setContentLength(length);
		return ;
	}

	


}
